package com.neusoft.Dao;
import com.neusoft.entity.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class JDBCTest {
	private static final String DRIVER_NAME = "com.mysql.jdbc.Driver";
	private static final String  URL = "jdbc:mysql://localhost:3306/test2";
	private static final String USER_NAME = "root";
	private static Connection connection = null;
	private static final String USER_PASSWORD = "mysqladmin";
	static
	{
		try {
			Class.forName(DRIVER_NAME);
			connection = DriverManager.getConnection(URL, USER_NAME, USER_PASSWORD);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch(SQLException e) {
			e.printStackTrace();
		}
	}
	//fanxing
	public List<User> getAllUsers()
	{
		PreparedStatement prepareStatement = null;
		ResultSet rs = null;
		String sql = "SELECT * FROM user";
		List<User> users = new ArrayList<>();
		try {
			prepareStatement = connection.prepareStatement(sql);
		    rs = prepareStatement.executeQuery();
			while(rs.next())
			{
				int id = rs.getInt(1);
				String userName = rs.getString(2);
				String password = rs.getString(3);
				User user = new User();
				user.setUserID(id );
				user.setUserName(userName);
				user.setUserPassword(password);
				users.add(user);
			}
		}
		catch(SQLException e) {
			e.printStackTrace();
		}finally
		{
			if(rs != null)
			{
				try {
					rs.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(prepareStatement!= null)
			{
				try {
					prepareStatement.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
			if(connection!= null)
			{
				try {
					connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
		
		return users;
	}
	
	public static void main(String[] args) {
		List<User> allUsers = new JDBCTest().getAllUsers();
		for(User user: allUsers) {
			System.out.println(user);
	}

	}
}
